package com.tdtech.keycloak.demo1.controller;

import com.tdtech.keycloak.demo1.dao.CustomerDAO;
import com.tdtech.keycloak.demo1.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;

@Controller
public class CustomerController {

    @Autowired
    private CustomerDAO customerDAO;

    /**
     * 首页
     * @return 首页
     */
    @GetMapping(path = "/")
    public String index() {

        return "external";
    }

    /**
     * 退出登录
     * @param request 请求对象
     * @return 重定向到首页
     * @throws Exception ServletException
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) throws Exception {
        request.logout();
        return "redirect:/";
    }

    /**
     * 新增一个用户
     * 该接口不需要登录
     * @return 用户列表
     */
    @GetMapping(path = "/addCustomer")
    @ResponseBody
    public List<Customer> addCustomer() {
        Customer customer = new Customer();
        customer.setAddress("四川成都天府大道南段");
        customer.setName("莫大胆");
        customer.setServiceRendered("简单的测试新增，无需登录");
        customerDAO.save(customer);
        return customerDAO.findAll();
    }

    /**
     * 查看用户列表
     * @param principal 登录信息
     * @param model model
     * @return 用户列表页面
     */
    @GetMapping(path = "/customers")
    public String customers(Principal principal, Model model) {
        model.addAttribute("customers", customerDAO.findAll());
        model.addAttribute("username", principal.getName());
        return "customers";
    }

}
